﻿using System;
using System.Configuration;
using SimpleServiceBus.Bus.MessageManagement;
using SimpleServiceBus.Utilities.ExpressionEval;

namespace SimpleServiceBus.Configuration
{
    public class MessageFilterConfigurationElement : ConfigurationElement
    {
        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get { return (string)base["name"]; }
            set { base["name"] = value; }
        }

        [ConfigurationProperty("enabled", DefaultValue = true, IsRequired = false)]
        public bool Enabled
        {
            get { return (bool)base["enabled"]; }
            set { base["enabled"] = value; }
        }

        [ConfigurationProperty("filterExpression",IsRequired = true)]
        public string FilterExpression
        {
            get { return (string)base["filterExpression"]; }
            set { base["filterExpression"] = value;}
        }

        [ConfigurationProperty("filterDirection",DefaultValue="both",IsRequired=false)]
        public string FilterDirection
        {
            get { return ((string)base["filterDirection"]).ToLower(); }
            set { base["filterDirection"] = value; }
        }

        [ConfigurationProperty("messageType")]
        protected string MessageTypeName
        {
            get { return (string)base["messageType"]; }
        }

        public Type MessageType
        {
            get
            {
                if (String.IsNullOrEmpty(MessageTypeName))
                    return typeof (object);

                return Type.GetType(MessageTypeName);
            }
        }
    }

    public class MessageFilterConfigurationCollection : ConfigurationElementCollection
    {
        public MessageFilterConfigurationElement this[int index]
        {
            get { return (MessageFilterConfigurationElement)BaseGet(index); }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                base.BaseAdd(index, value);
            }
        }

        public override ConfigurationElementCollectionType CollectionType
        {
            get { return ConfigurationElementCollectionType.BasicMap; }
        }

        protected override string ElementName
        {
            get { return "filter"; }
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new MessageFilterConfigurationElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((MessageFilterConfigurationElement)element).Name;
        }
    }
}
